package org.kingtop.mybatis.persistence.metamodel;

import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.type.JdbcType;
import org.kingtop.mybatis.util.JdbcConstants;

/**
 * java类型对应数据库的默认数据类型，主要用于当值为null的时候，数据库插入不会报错 现在只做了对应于oracle的部分
 *
 * @author 陈金波
 * @date 2018年1月4日 下午3:15:07
 * @Copyright: 2018 chen jinbo. All rights reserved.
 */
public enum DbTypeEnum {

	STRING_ORACLE(JdbcConstants.ORACLE, JdbcType.VARCHAR, String.class), // String.class
	LONG_ORACLE(JdbcConstants.ORACLE, JdbcType.NUMERIC, Long.class), // Long.class
	INTEGER_ORACLE(JdbcConstants.ORACLE, JdbcType.NUMERIC, Integer.class), // Integer.class
	DATE_ORACLE(JdbcConstants.ORACLE, JdbcType.DATE, Date.class), // Date.class
	LOCAL_DATE_ORACLE(JdbcConstants.ORACLE, JdbcType.DATE, LocalDate.class), // LocalDate.class
	LOCAL_DATE_TIME_ORACLE(JdbcConstants.ORACLE, JdbcType.DATE, LocalDateTime.class), // LocalDateTime.class
	CHARACTER_ORACLE(JdbcConstants.ORACLE, JdbcType.CHAR, Character.class),// Character.class
	
	STRING_MYSQL(JdbcConstants.MYSQL, JdbcType.VARCHAR, String.class),
	LONG_MYSQL(JdbcConstants.MYSQL, JdbcType.BIGINT, Long.class),
	INTEGER_MYSQL(JdbcConstants.MYSQL, JdbcType.INTEGER, Integer.class),
	DATE_MYSQL(JdbcConstants.MYSQL, JdbcType.DATE, Date.class),
	LOCAL_DATE_MYSQL(JdbcConstants.MYSQL, JdbcType.DATE, LocalDate.class),
	LOCAL_DATE_TIME_MYSQL(JdbcConstants.MYSQL, JdbcType.DATE, LocalDateTime.class),
	CHARACTER_MYSQL(JdbcConstants.MYSQL, JdbcType.VARCHAR, Character.class),
	;

	/**
	 * 数据库类型
	 */
	private String dbType;

	/**
	 * jdbc对应于数据库的类型
	 */
	private JdbcType jdbcType;

	/**
	 * java的数据类型
	 */
	private Class<?> javaType;

	/**
	 * 缓存所有的关系，方便查找
	 */
	private static Map<DbTypeKey, DbTypeEnum> codeLookup = new HashMap<DbTypeKey, DbTypeEnum>();

	// 初始化缓存
	static {
		for (DbTypeEnum type : DbTypeEnum.values()) {
			codeLookup.put(new DbTypeKey(type.getDbType(), type.getJavaType()), type);
		}
	}

	private DbTypeEnum(String dbType, JdbcType jdbcType, Class<?> javaType) {
		this.dbType = dbType;
		this.jdbcType = jdbcType;
		this.javaType = javaType;
	}

	/**
	 * 通过数据库类型和java类型查找对应的枚举
	 * 
	 * @author 陈金波
	 * @date 2018年1月4日 下午3:27:28
	 * @param dbType
	 *            数据库类型
	 * @param javaType
	 *            java类型
	 * @return
	 * @return DbTypeEnum 对应的枚举，找不到返回null
	 */
	public static DbTypeEnum forJavaType(String dbType, Class<?> javaType) {
		try {
			return codeLookup.get(new DbTypeKey(dbType, javaType));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String getDbType() {
		return dbType;
	}

	public void setDbType(String dbType) {
		this.dbType = dbType;
	}

	public JdbcType getJdbcType() {
		return jdbcType;
	}

	public void setJdbcType(JdbcType jdbcType) {
		this.jdbcType = jdbcType;
	}

	public Class<?> getJavaType() {
		return javaType;
	}

	public void setJavaType(Class<?> javaType) {
		this.javaType = javaType;
	}

}
